const fs   = require('fs')
const path = require('path')
const http = require('http')
const qs = require('querystring')
const server= http.createServer()


server.on('request',(rqs,res)=>{
    // console.log(rqs.url);
    if(rqs.url === '/provinceName'){
        // console.log(1);
       fs.readFile(path.join(__dirname,'data/city.json',),(err,data)=>{
        if(err) return console.log(err);
        // console.log(data.toString());
        const arr =  JSON.parse(data).map(i=> i.provinceName)
        console.log(arr);
        res.setHeader('Content-Type', 'application/json;charset=utf-8')
        res.end(JSON.stringify(arr))
    //    console.log(panme);
       })
    }else if(rqs.url.startsWith('/city')){
    //   console.log(1);
     
    
    fs.readFile(path.join(__dirname,'data/city.json',),(err,data)=>{
    

    const string =  rqs.url.split('?')[1] 
    const srt    =  rqs.url.split('?')[2] 
    //把数据转换成对象
    const obj2 = qs.parse(srt)

    const obj = qs.parse(string)
    console.log(obj2);
    console.log(obj);
//    console.log(string);

   
    const cityobj =  JSON.parse(data).find(i=> i.provinceName === obj.panme )
    const xx = cityobj.cities.map(i=>{ 
    return i.cityName
   
 });
  if(obj.panme){
     console.log(obj.panme);
     if(obj.canme){
      console.log(obj.canme);
     }
  }
        
//  console.log(xx);

 res.setHeader('Content-Type', 'application/json;charset=utf-8')
 res.end(JSON.stringify(xx))
    // console.log(obj.panme); 
    // console.log(arr[obj.panme]);
    // for (let key in cityobj) {
    // }
     } )}  else{
        res.setHeader('Content-Type', 'application/json;charset=utf-8')
        console.log('没有数据');
        res.end('没有数据')
    }
})


server.listen(3000,()=>{
    console.log('启动服务器');
})